#!/usr/bin/python3
# -*- coding: utf-8 -*-
# File  : utils.py
# Author: anyongjin
# Date  : 2020/8/14
import logging
import yaml
import os
import platform

src_dir = os.path.dirname(__file__).replace('\\', '/')
default_cfg_path = os.path.join(src_dir, 'task_config.yml')


left_braces = ['(', '（', '【']
right_braces = [')', '）', '】']


def get_logger(logger_name=None, level=logging.INFO):
    logger = logging.getLogger(logger_name)
    logger.setLevel(level)

    ch = logging.StreamHandler()
    ch.setLevel(level)

    formatter = logging.Formatter('%(asctime)s %(process)d %(levelname)s %(message)s')
    ch.setFormatter(formatter)

    if not logger.handlers:
        logger.addHandler(ch)
    return logger


logger = get_logger(level=logging.WARNING)


def get_config(config_path=None):
    path = config_path or default_cfg_path
    content = open(path, 'r', encoding='utf-8').read()
    if platform.system() == 'Windows':
        content = content.replace('/data/', 'D:/')
    return yaml.safe_load(content)


def clean_text(content):
    '''
    清除content前后非文本字符
    如果content中包含括号，则判断是否保留括号内容
      括号内文本长度小于4，括号前本文长度大于2，倒叙排序后首个文本字符位置在括号内则保留括号，否则移除括号及括号内容
      eg 中国石油大学(北京)  保留  中国石油大学（计算机学院)=>中国石油大学
    '''
    first_text_id = index_of_text_char(content)
    if first_text_id >= 0:
        content = content[first_text_id:]
    else:
        content = []
    if not content or len(content) == 0:
        return content or ''
    content = content[::-1]
    first_text_id = index_of_text_char(content)
    if first_text_id > 0:
        left_brace_id = get_index_in_string(content, left_braces)
        right_brace_id = get_index_in_string(content, right_braces)
        if 0 <= right_brace_id < left_brace_id and len(content) - left_brace_id > 2 and \
                right_brace_id < first_text_id < left_brace_id:
            first_text_id = right_brace_id if left_brace_id - right_brace_id < 5 else left_brace_id + 1
        content = content[first_text_id:]
    content = content[::-1]
    return content or ''


def index_of_text_char(string, strict=True, keep_chars=[]):
    '''获取字符串中第一个文本字符的索引，如果没有返回-1'''
    if not isinstance(string, str) and not isinstance(string, list) and not isinstance(string, tuple):
        return -1
    if not keep_chars:
        keep_chars = []
    for i in range(len(string)):
        if string[i] in keep_chars:
            return i
        if strict:
            if is_text_char(string[i]):
                return i
            else:
                continue
        elif len(string[i].replace(' ', '').replace('　', '').replace('\xa0', '').replace('\n', '')) > 0:
            return i
    return -1


def is_text_char(char):
    return '\u4e00' <= char <= '\u9fa5' or \
           '0' <= char <= '9' or \
           'Z' >= char >= 'A' or 'a' <= char <= 'z'


def get_index_in_string(string, search_list):
    '''
    从字符串中查找所有要搜索的字符串下标\n
    'string'  'This is a test' or ['This',' ','is',' ','a',' ','test']\n
    'search_list' ['is','t']\n
    RETURN 2
    '''
    dic = get_indexs_in_string(string, search_list)
    if dic:
        return min(dic.values())
    return -1


def get_indexs_in_string(string, search_list):
    '''
    从字符串中查找所有要搜索的字符串左侧下标\n
    'string'  'This is a test' or ['This',' ','is',' ','a',' ','test']\n
    'search_list' ['is','t']\n
    RETURN {'is':2,'t':10}
    '''
    dic = {}
    for s in search_list:
        idx = -1
        if isinstance(string, str):
            idx = string.find(s)
        elif isinstance(string, (list, tuple)):
            if s in string:
                idx = string.index(s)
        if idx >= 0 and (s not in dic or idx < dic[s]):
            dic[s] = idx
    return dic

